<template>
  <div class="app-container customer-div">
    <div style="margin-top: 20px">
      <!--搜索-->
      <el-form :inline="true" :model="listQuery" size="mini" label-width="100px">
        <el-form-item label="月份：">
          <el-date-picker
                  v-model="listQuery.month"
                  type="month"
                  format="yyyy 年 MM 月"
                  value-format="yyyy-MM"
                  range-separator="-"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="业务员：">
          <el-select
            style="width: 100px"
            v-model="listQuery.userId"
            filterable
            clearable
          >
            <el-option
              v-for="item in userOptionList"
              :key="item.userId"
              :label="item.userName"
              :value="item.userId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="事业部：">
          <el-select v-model="listQuery.groupName" filterable clearable>
            <el-option
              v-for="(item,index) in groupSetList"
              :key="index"
              :label="item"
              :value="item">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button
                  @click="handleSearchList()"
                  type="primary">
            查询
          </el-button>
          <el-button
            v-if="profitAddSalesReportExport"
            :loading="btnLoading2"
            @click="downloadExcel"
            type="primary">
            报表导出
          </el-button>
          <el-button
            v-if="profitAddSalesReportSet"
            @click="showPop()"
            type="primary">
            目标设置
          </el-button>
          <el-button
            v-if="brandSaleTargetImport"
            @click="showImport2()"
            type="success">
            销量目标导入
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!--数据列表-->
    <div class="table-container">
      <el-table
        :span-method="objectSpanMethod"
        v-loading="loading"
        :data="list"
        border
        style="width: 100%; margin-top: 0px">
        <el-table-column
          align="center"
          label="人员">
          <el-table-column
            label="事业部"
            prop="groupName"
            align="center"
            min-width="100">
          </el-table-column>
          <el-table-column
            label="业务员"
            prop="realName"
            align="center"
            min-width="100">
          </el-table-column>
        </el-table-column>
        <el-table-column
                align="center"
                label="毛利">
          <el-table-column
            prop="profitTargetNum"
            align="center"
            label="本月毛利目标"
            min-width="100">
          </el-table-column>
          <el-table-column
            prop="profitActualNum"
            align="center"
            label="个人完成值"
            min-width="100">
          </el-table-column>
          <el-table-column
            prop="profitFinishedRate"
            align="center"
            label="本月个人完成率"
            min-width="100">
          </el-table-column>
          <el-table-column
            prop="profitDiffRate"
            align="center"
            label="节点完成差异率"
            min-width="100">
          </el-table-column>
        </el-table-column>
        <el-table-column
          align="center"
          label="销量">
          <el-table-column
            prop="todayGoodsNum"
            align="center"
            label="今日合同量"
            min-width="100">
          </el-table-column>
          <el-table-column
            prop="allGoodsNum"
            align="center"
            label="本月销售总吨数"
            min-width="100">
          </el-table-column>
          <el-table-column
            prop="orderNumTargetNum"
            align="center"
            label="本月销售目标"
            min-width="100">
          </el-table-column>
          <el-table-column
            prop="orderNumFinishedRate"
            align="center"
            label="本月个人销售完成率"
            min-width="100">
          </el-table-column>
          <el-table-column
            prop="orderNumDiffRate"
            align="center"
            label="节点完成差异率"
            min-width="100">
          </el-table-column>
          <el-table-column
            prop="shipActualNum"
            align="center"
            label="当月出库总吨数"
            min-width="100">
          </el-table-column>

        </el-table-column>
      </el-table>
    </div>

    <el-dialog
      :close-on-click-modal="false"
      title="目标设置"
      :visible.sync="dialogVisible"
      width="660px">
      <div>
        <el-form size="mini" label-width="80px" ref="form" :rules="rules" :model="form">
          <el-table
            :data="form.targetList"
            :span-method="objectSpanMethod"
            border
            height="500px"
            style="width: 100%;">
            <el-table-column
              align="center"
              label="人员">
              <el-table-column
                prop="groupName"
                label="事业部"
                align="center"
                min-width="100">
              </el-table-column>
              <el-table-column
                prop="realName"
                label="业务员"
                align="center"
                min-width="100">
              </el-table-column>
            </el-table-column>
            <el-table-column
              align="center">
              <template slot="header" slot-scope="scope">
                <el-form-item prop="month" label="目标月份" style="margin-bottom: 0">
                  <el-date-picker
                    @change="getFormList"
                    v-model="form.month"
                    format="yyyy 年 MM 月"
                    value-format="yyyy-MM"
                    type="month"
                    placeholder="选择月">
                  </el-date-picker>
                </el-form-item>
              </template>

              <el-table-column
                label="本月毛利目标"
                align="center"
                min-width="180">
                <template slot-scope="scope">
                  <el-form-item label-width="0px" v-if="scope.row.realName.indexOf('汇总')==-1 && scope.row.groupName != '整体汇总'" :prop="`targetList.${scope.$index}.profitTargetNum`" :rules="rules.profitTargetNum" style="margin-bottom: 0">
                    <el-input v-model="scope.row.profitTargetNum"  type="number"></el-input>
                  </el-form-item>
                  <div v-if="scope.row.realName=='销售汇总'">{{form.targetList | fifdepartment(scope.row.groupName,'profitTargetNum','sale')}}</div>
                  <div v-if="scope.row.realName=='采销汇总'">{{form.targetList | fifdepartment(scope.row.groupName,'profitTargetNum','all')}}</div>
                  <div v-if="scope.row.groupName == '整体汇总'">{{form.targetList | fifall('profitTargetNum')}}</div>
                </template>
              </el-table-column>
              <el-table-column
                label="本月销售目标"
                align="center"
                min-width="180">
                <template slot-scope="scope">
                  <el-form-item label-width="0px" v-if="scope.row.realName.indexOf('汇总')==-1&& scope.row.groupName != '整体汇总'" :prop="`targetList.${scope.$index}.orderNumTargetNum`" :rules="rules.orderNumTargetNum" style="margin-bottom: 0">
                    <el-input v-model="scope.row.orderNumTargetNum"  type="number" ></el-input>
                  </el-form-item>
                  <div v-if="scope.row.realName == '销售汇总'">{{form.targetList | fifdepartment(scope.row.groupName,'orderNumTargetNum','sale')}}</div>
                  <div v-if="scope.row.realName == '采销汇总'">{{form.targetList | fifdepartment(scope.row.groupName,'orderNumTargetNum','all')}}</div>
                  <div v-if="scope.row.groupName == '整体汇总'">{{form.targetList | fifall('orderNumTargetNum')}}</div>
                </template>
              </el-table-column>
            </el-table-column>
          </el-table>
        </el-form>

      </div>
      <span slot="footer" class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="handleConfirm" :loading="btnLoading">确 定</el-button>
      </span>
    </el-dialog>

    <!--目标记录导入-->
    <el-dialog
      :show-close="showClose2"
      :close-on-click-modal="showClose2"
      :close-on-press-escape="showClose2"
      title="销量目标导入"
      :beforeClose="beforeCloseEditPrice2"
      :visible.sync="dialogVisibleImprot2"
      width="500px">
      <div>
        <el-alert
          title="请先按约定好的字段导入销量目标"
          type="warning"
          :closable="false">
        </el-alert>
        <div class="upload-div" style="margin-top:20px">
          <input id="upload" type="file" @change="importfxx(this)" accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" />
          <el-button type="primary" size="small" :loading="uploadLoading">选择上传文件</el-button>
        </div>
        <div style="margin:20px auto;margin-bottom:0;word-break:break-all;text-align: left;line-height:20px;background: #fef0f0;color:#f56c6c;padding:10px" v-if="msg2!=''">
          <div style="max-height: 90px;overflow: auto;padding:10px"><div v-if="showFial2">添加失败：</div>{{msg2}}</div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="handleEditPriceConfirm2" :loading="EditLoading2">提 交</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
    import { groupSetListAPI,saleTarget,saleTargetSet } from '@/api/order';
    import { getOrderUsersList } from "@/api/partner";
    import {brandSaleTargetImport} from '@/api/data'
    import {formatDate} from '@/utils/date';
    import store from '@/store'
    import { mapGetters } from 'vuex'
    import XLSX from "xlsx";
    const defaultListQuery = {
      pageNum: 1,
      pageSize: 10,
      groupName: '',//组名称
      month:'',
      userId:''
    };
    const defaultForm = {
      targetList:[],
      month:''
    };
    export default {
        name: "profitAddSalesReport",
        data(){
            return{
                roles:store.getters.roles ? store.getters.roles : [],
                listQuery: JSON.parse(JSON.stringify(defaultListQuery)),
                list:[],
                loading:false,
                groupSetList:[],
                dialogVisible:false,
                form:JSON.parse(JSON.stringify(defaultForm)),
                btnLoading:false,
                rules:{
                  orderNumTargetNum:[{required: true, trigger: 'blur' ,message: ' '}],
                  profitTargetNum:[{required: true, trigger: 'blur' ,message: ' '}],
                  month:[{required: true, trigger: 'blur' ,message: ' '}],
                },
                btnLoading2:false,
                userOptionList:[],

                showClose2:true,
                dialogVisibleImprot2:false,//批量导入弹窗
                EditLoading2:false,//批量导入提交按钮loadin
                showFial2:false,//批量导入失败
                msg2:'',//上传文件信息
                uploadLoading:false,
                da:[],
                file:null,
            }
        },
        computed: {
          ...mapGetters([
            'name',
            'mobile',
            'userId'
          ]),
          profitAddSalesReportSet() {
            if(this.roles.indexOf("profitAddSalesReportSet") != -1){
              return true
            }else{
              return false
            }
          },
          profitAddSalesReportExport() {
            if(this.roles.indexOf("profitAddSalesReportExport") != -1){
              return true
            }else{
              return false
            }
          },

          brandSaleTargetImport(){
            if(this.roles.indexOf("brandSaleTargetImport") != -1){
              return true
            }else{
              return false
            }
          },


        },
        created() {
          let now = new Date();
          let nowMonth = now.getMonth(); //当前月
          let nowYear = now.getFullYear(); //当前年
          //本月的开始时间
          let monthStartDate = new Date(nowYear, nowMonth, 1);
          let startDate = formatDate(monthStartDate, 'yyyy-MM');
          this.listQuery.month = startDate;
          this.getListData();
          this.getGroupSetList()
          this.getUserOptionList()
        },
        filters: {
          fifdepartment(list,department,key,type) {
                let sum = 0
                let saleSum = 0
                let newlist = list.filter((el)=>{
                  return el.groupName == department
                })
                newlist.forEach((el)=>{
                  if(el.realName.indexOf('汇总')==-1){
                    let item = el[key] ? parseFloat(el[key]) :0
                    sum = sum + item
                    if(el.isPurchase == 0){
                      saleSum = saleSum + item
                    }
                  }
                })
                if(type == 'sale'){
                  return  saleSum
                }else{
                  return sum
                }
          },
          fifall(list,key) {
            let sum = 0
            list.forEach((el)=>{
              if(el.realName.indexOf('汇总')==-1&& el.groupName != '整体汇总'){
                let item = el[key] ? parseFloat(el[key]) :0
                sum = sum + item
              }
            })
            return sum
          },
        },
        methods:{
          //导入excel
          importfxx(obj) {
            let _this = this;
            this.uploadLoading = true;
            let inputDOM = this.$refs.inputer;
            // 通过DOM取文件数据
            this.file = event.currentTarget.files[0];
            var rABS = false; //是否将文件读取为二进制字符串
            var f = this.file;
            var reader = new FileReader();
            //if (!FileReader.prototype.readAsBinaryString) {
            FileReader.prototype.readAsBinaryString = function(f) {
              var binary = "";
              var rABS = false; //是否将文件读取为二进制字符串
              var pt = this;
              var wb; //读取完成的数据
              var outdata;
              var reader = new FileReader();
              reader.onload = function(e) {
                var bytes = new Uint8Array(reader.result);
                var length = bytes.byteLength;
                for(var i = 0; i < length; i++) {
                  binary += String.fromCharCode(bytes[i]);
                }
                var XLSX = require('xlsx');
                if(rABS) {
                  wb = XLSX.read(btoa(fixdata(binary)), { //手动转化
                    type: 'base64'
                  });
                } else {
                  wb = XLSX.read(binary, {
                    type: 'binary'
                  });
                }
                outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);//outdata就是你想要的东西
                // if (outdata.length  > 200){
                //   _this.$message({
                //     message: '最大上传200条',
                //     type: 'error'
                //   });
                //   var test = document.getElementById('upload');
                //   test.value = '';
                //   return false;
                // }
                let list = [...outdata];
                console.log("list",list)
                console.log("da",_this.da)
                _this.da = []
                list.forEach((el)=>{
                  for (let key in el) {
                    if(key != '姓名'){
                      let keyArray = key.split("_")
                      let className = keyArray[0] ? keyArray[0] : undefined
                      let brandName=keyArray[1] ? keyArray[1] : undefined
                      _this.da.push({
                        '姓名':el['姓名'],
                        '品名':className,
                        '厂家':brandName,
                        '销量':el[key]
                      })
                    }
                  }
                })
                // console.log("_this.da",_this.da)
                let arr = [];

                let para = {
                  withList: arr
                };
                _this.$message({
                  message: '上传成功，请点击提交',
                  type: 'success'
                });
                _this.uploadLoading = false;
              };
              reader.readAsArrayBuffer(f);
            };
            if(rABS) {
              reader.readAsArrayBuffer(f);
            } else {
              reader.readAsBinaryString(f);
            }
          },

          //显示导入记录弹窗
          showImport2(){

            this.showFial2 = false;
            this.EditLoading2 = false;
            this.uploadLoading = false;
            this.msg2 = '';
            this.dialogVisibleImprot2 = true;
          },
          //关闭导入跟进记录弹窗
          beforeCloseEditPrice2(){
            $("#upload").val('');
            this.da = [];
            this.msg2 = '';
            this.dialogVisibleImprot2 = false;
          },
          //提交导入销量目标
          handleEditPriceConfirm2(){
            if (this.da.length == 0){
              this.$message({
                message: '上传数据为空',
                type: 'warning'
              });
              return false;
            }
            this.msg2 = '后台处理中，请耐心等待……';
            this.showFial2 = false;
            this.EditLoading2 = true;
            this.showClose2 = false;
            console.log(this.da)
            brandSaleTargetImport({list:this.da}).then((res)=>{
              this.$message({
                message: '销量目标导入成功',
                type: 'success'
              });
              this.msg2 = '销量目标导入成功';
              this.EditLoading2 = false;
              this.dialogVisible2 = false;
              this.showClose2 = true;
              this.da = [];
              this.dialogVisibleImprot2 = false;
              $("#upload").val('');
              this.getUserList();
            }).catch((err)=>{
              this.msg2 = err.msg;
              this.showFial2 = true;
              this.EditLoading2 = false;
              $("#upload").val('');
              this.showClose2 = true;
            })
          },

          //获取员工下拉选项
          getUserOptionList() {
            getOrderUsersList().then((res) => {
              this.userOptionList = res;
            });
          },
          //下载excle
          downloadExcel(){
            let params
            params = JSON.parse(JSON.stringify(this.listQuery));
            params.isExport = 1;
            delete params.pageSize;
            delete params.pageNum;
            this.btnLoading2 = true
            saleTarget(params).then((res)=>{
              this.btnLoading2 = false;
              require.ensure([], () => {
                const { export_json_to_excel } = require('sheet/Export2Excel');
                const tHeader = res.title;
                const filterVal = res.columns;
                const list = res.list;
                const data = this.formatJson(filterVal, list);
                export_json_to_excel(tHeader, data, res.fileName);
              })
            }).catch(()=>{
              this.btnLoading2 = false;
            })
          },

          //下载表格数据格式化
          formatJson(filterVal, jsonData) {
            return jsonData.map(v => filterVal.map(j => v[j]))
          },

          newList(oldList){
            let list = JSON.parse(JSON.stringify(oldList))
            let sum = 0
            list.forEach((el,index)=>{
              list[index]['mergeSum'] = 0
              if(index < list.length-1 && list[index]['groupName'] == list[index+1]['groupName']){
                sum = sum+1
              }else if(index == list.length-1){
                list[index]['mergeSum'] = 0
              }else{
                sum = sum+1
                list[index+1-sum]['mergeSum'] = sum
                sum = 0
              }
            })
            return list
          },
          getFormList(){
            saleTarget({month:this.form.month}).then((res)=>{
              this.form.targetList = [];
              let oldlist = []
              res.forEach((el)=>{
                oldlist.push({
                  userId: el.userId, //用户ID
                  groupName: el.groupName,//组名
                  realName: el.realName, //姓名
                  profitTargetNum:el.profitTargetNum,
                  orderNumTargetNum:el.orderNumTargetNum,
                  isPurchase:el.isPurchase
                })
              })
              this.form.targetList = this.newList(oldlist)
            }).catch(()=>{

            })
          },
          showPop(){
            this.dialogVisible = true
            let now = new Date();
            let nowMonth = now.getMonth(); //当前月
            let nowYear = now.getFullYear(); //当前年
            //本月的开始时间
            let monthStartDate = new Date(nowYear, nowMonth, 1);
            let startDate = formatDate(monthStartDate, 'yyyy-MM');
            this.form.month = startDate;
            this.getFormList()

          },
          handleClose(){
            this.dialogVisible = false
          },
          handleConfirm(){
            this.$refs['form'].validate((valid) => {
              if (valid) {
                this.btnLoading = true;
                let data = {}
                data.month = this.form.month
                data.targetList = []
                this.form.targetList.forEach((el)=>{
                  if(el.realName.indexOf('汇总')==-1 && el.groupName != '整体汇总'){
                    data.targetList.push({
                      userId:el.userId,
                      profitTargetNum : el.profitTargetNum,
                      orderNumTargetNum : el.orderNumTargetNum
                    })
                  }
                })
                saleTargetSet(data).then(()=>{
                  this.btnLoading = false;
                  this.handleClose()
                  this.getListData()
                }).catch(()=>{
                  this.btnLoading = false;
                })
              }
            })
          },
          objectSpanMethod({ row, column, rowIndex, columnIndex }) {
            if (columnIndex === 0) {
              if (row.mergeSum > 0) {
                return {
                  rowspan: row.mergeSum,
                  colspan: 1
                };
              }else if(row.groupName == '整体汇总'){
                return {
                  rowspan: 1,
                  colspan: 2
                };
              }else {
                return {
                  rowspan: 0,
                  colspan: 0
                };
              }
            }else if(columnIndex === 1 && row.groupName == '整体汇总'){
              return {
                rowspan: 0,
                colspan: 0
              };
            }
          },

          //获取小组列表
          getGroupSetList(){
            groupSetListAPI().then((res) => {
              this.groupSetList = res.groupList;
            })
          },
            handleSearchList(){
                this.getListData();
            },


            getListData(){
              this.loading = true;
              saleTarget(this.listQuery).then((res)=>{
                this.list = this.newList(res);
                this.loading = false;
              }).catch(()=>{
                this.loading = false;
              })
            },

        },
    }
</script>
<style scoped lang="scss">

.upload-div{
  text-align: center;
  position:relative;
  #upload{
    opacity: 0;
    position: absolute;
    z-index: 1;
    width:154px;
    height:40px
  }
}
</style>



